// var SERVERURL = "http://chehu.ikaibei.com";
// var SERVERURL = "http://www.chehuvip.com";
// var SERVERURL = "http://www.unitexiaowei.top";
var SERVERURL = "http://118.190.152.225";

window.alert = function (name) {
    var iframe = document.createElement("IFRAME");
    iframe.style.display = "none";
    iframe.setAttribute("src", 'data:text/plain,');
    document.documentElement.appendChild(iframe);
    window.frames[0].window.alert(name);
    iframe.parentNode.removeChild(iframe);
};

function getUrlVars(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?')+1).split('&');
    for(var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

// 通过js适配不同的屏幕大小
(function (doc, win) {
    var docEl = doc.documentElement,
        resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
        recalc = function () {
            var clientWidth = docEl.clientWidth;
            if (!clientWidth) return;
            // 根据设备的比例调整初始font-size大小
            // if(clientWidth > 750) clientWidth = 750;
            docEl.style.fontSize = 20 * (clientWidth / 375) + 'px';
        };
    if (!doc.addEventListener) return;
    win.addEventListener(resizeEvt, recalc, false);
    doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);

// var browser = {
//     versions: function () {
//         var u = navigator.userAgent, app = navigator.appVersion;
//         return {//移动终端浏览器版本信息
//             trident: u.indexOf('Trident') > -1, //IE内核
//             presto: u.indexOf('Presto') > -1, //opera内核
//             webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
//             gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
//             mobile: !!u.match(/AppleWebKit.*Mobile.*/) , //是否为移动终端
//             ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
//             android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
//             iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器
//             iPad: u.indexOf('iPad') > -1, //是否iPad
//             webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
//         };
//     }()
// }
// if (!browser.versions.mobile ) {
//     // window.location.href="http://www.klgwl.cn/"
// }

//微信授权
function wx_authorize() {
    var user_id = getCookie("chehu_id");
    var open_id = getUrlVars().openid;
    if(open_id){
        var nickname = decodeURIComponent(getUrlVars().nickname);
        var headimgurl = getUrlVars().headimgurl;
        // //console.log(open_id);
        // //console.log(decodeURIComponent(nickname));
        // //console.log(headimgurl);
        // return;
        _loadshow("登录中");
        $.ajax({
            // url:SERVERURL + '/api/CarApi/Login',
            url:SERVERURL + '/v2/api/carapi/Login',
            dataType:'JSON',
            type:'POST',
            data:{
                isPhoneLogin:0,
                // mobile:tel,
                // password:password,
                open_id:open_id,
                photo:headimgurl,
                name:nickname
            },
            success:function(res){
                if(typeof res == "string"){
                    res = JSON.parse(res)
                }
                // console.log(res);
                setCookie("chehu_id",res.data.id);
                setCookie("chehu_username",res.data.username);
                setCookie("chehu_photo",res.data.photo);
                setCookie("chehu_openid",res.data.open_id);
                // return;
                check_login();
                var url = window.location.href;
                var arr = url.split('?');
                var ar = arr[0];
                window.location.href = ar;
            },
            error:function(XMLHttpRequest, textStatus, errorThrown) {
                //console.log(XMLHttpRequest.status);
                //console.log(XMLHttpRequest.readyState);
                //console.log(textStatus);
            }
        });
        return false;
    }
    if(!user_id){
        window.location.href = "http://www.chehuvip.com/chehu_wx/Wxauthorize/index.php";
        return false;
    }
}
// wx_authorize();
// //console.log(getUrlVars().headimgurl);

//点击头像打开个人中心
// $(".topbox").on("click",".index-top-headimg",function () {
//     var _member_pop = $(".topbox").find(".member-pop");//个人中心弹窗
//     var _member_pop_mask = $(".topbox").find(".member-pop-mask");//个人中心弹窗背景遮罩
//     var _member_pop_close = $(".topbox").find(".member-pop-close");//个人中心弹窗关闭按钮
//     _member_pop.fadeIn(100);
//     _member_pop_mask.on("click",function () {
//         _member_pop.fadeOut(100);
//     });
//     _member_pop_close.on("click",function () {
//         _member_pop.fadeOut(100);
//     });
// });
$(".topbox").on("click",".index-top-member-btn",function () {
    var _personal_box = $(".topbox").find(".personal-box");//个人中心侧栏
    var _personal_box_mask = $(".topbox").find(".personal-box-mask");//个人中心侧栏背景遮罩
    var _personal_box_board = $(".topbox").find(".personal-box-board");//个人中心侧栏主内容盒子
    _personal_box.fadeIn(0,function () {
        _personal_box.addClass("active");
    });
    _personal_box_mask.on("click",function () {
        _personal_box.removeClass("active");
        setTimeout(function () {
            _personal_box.hide();
        },300);
    });
    if(getCookie("chehu_id")){
        $.ajax({
            url:SERVERURL + '/api/WechatChehuApi/getUserIntegral?user_id=' + getCookie("chehu_id"),
            type:'GET',
            success:function (res) {
                console.log(res);
                var data = res.data;
                $(".topbox").find(".my-top-level").text("LV" + data.grade);//等级
                $(".topbox").find(".my-top-score").text(data.integral);//积分
            }
        });
    }
});

//搜索聚焦
$(".topbox").on("focus",".index-top-search-input",function () {
    var _this = $(this);
    var _index_top_searchbox = $(".topbox").find(".index-top-searchbox");//搜索盒子
    _this.addClass("active");
    _index_top_searchbox.addClass("active");
    var _moretab_pop = $(".topbox").find(".moretab-pop");//更多栏目弹窗
    _moretab_pop.fadeOut(100);
    $(".topbox").find(".search-pop").fadeIn(100);
    get_search_history();
});
$(".topbox").on("focusout blur",".index-top-search-input",function () {
    var _this = $(this);
    var _index_top_search_input = $(".topbox").find(".index-top-search-input");//顶栏搜索框
    var _index_top_searchbox = $(".topbox").find(".index-top-searchbox");//搜索盒子
    _index_top_searchbox.removeClass("active");
    if(!_index_top_search_input.val()){
        _this.removeClass("active");
    }
});
$(".topbox").on("click",".index-top-search-inputbtn",function () {
    var _this = $(this);
    var _index_top_search_input = _this.find(".index-top-search-input");//顶栏搜索框
    _index_top_search_input.focus();
});
//关闭搜索弹窗
$(".topbox").on("click",".search-pop-close",function () {
    $(".topbox").find(".search-pop").fadeOut(100);
});

//顶栏搜索按钮
$(".topbox").on("touchend",".index-top-search-btn",function () {
    var _this = $(this);
    var _index_top_search_input = $(".topbox").find(".index-top-search-input");//顶栏搜索框
    var search_val = _index_top_search_input.val();//搜索值
    if(!search_val){
        alert("请输入搜索内容");
        return false;
    }
    var chehu_search_group = getCookie("chehu_search");
    if(chehu_search_group){
        chehu_search_group = chehu_search_group.split(",");
    }else{
        chehu_search_group = [];
    }
    for(var i = 0; i < chehu_search_group.length; i++){
        if(search_val == chehu_search_group[i]){
            chehu_search_group.splice(i,1);
        }
    }
    chehu_search_group.unshift(search_val);
    if(chehu_search_group.length > 10){
        chehu_search_group.pop();
    }
    chehu_search_group = chehu_search_group.toString();
    setCookie("chehu_search",chehu_search_group);
    var _search_pop_history_clearall = $(".topbox").find(".search-pop-history-clearall");//清空搜索历史按钮
    _search_pop_history_clearall.removeClass("active");
    get_search_history();
    $(".topbox").find(".search-pop").fadeOut(100);
    window.location.href = "search.html?searchval=" + search_val;
});
//载入历史搜索内容
function get_search_history() {
    var _search_pop_historybox = $(".topbox").find(".search-pop-historybox");//搜索历史列表盒子
    var _search_pop_history_clearall = $(".topbox").find(".search-pop-history-clearall");//清空搜索历史按钮
    var chehu_search_group = getCookie("chehu_search");
    if(!chehu_search_group){
        _search_pop_history_clearall.addClass("active");
        return false;
    }
    chehu_search_group = chehu_search_group.split(",");
    _search_pop_historybox.empty();
    for(var i = 0; i < chehu_search_group.length; i++){
        _search_pop_historybox.append(
            '<div class="search-pop-history-list">' +
            '<div class="search-pop-history-list-icon iconfont icon-lishi"></div>' +
            '<div class="search-pop-history-list-word">' + chehu_search_group[i] + '</div>' +
            '<div class="search-pop-history-list-clear iconfont icon-guanbi"></div>' +
            '</div>'
        );
    }
}

//清空历史搜索记录
$(".topbox").on("click",".search-pop-history-clearall-haverecord",function () {
    var _this = $(this);
    delCookie("chehu_search");
    $(".topbox").find(".search-pop-historybox").empty();
    $(".topbox").find(".search-pop-history-clearall").addClass("active");
    alert("清空成功");
});

//单个删除搜索记录
$(".topbox").on("click",".search-pop-history-list-clear",function () {
    var _this = $(this);
    var del_index = _this.parents(".search-pop-history-list").index();
    var chehu_search_group = getCookie("chehu_search");
    chehu_search_group = chehu_search_group.split(",");
    chehu_search_group.splice(del_index,1);
    if(chehu_search_group.length <= 0){
        $(".topbox").find(".search-pop-history-clearall").addClass("active");
    }
    chehu_search_group = chehu_search_group.toString();
    setCookie("chehu_search",chehu_search_group);
    _this.parents(".search-pop-history-list").fadeOut(300);
});

//点击顶部更多打开更多栏目
$(".topbox").on("click",".index-top-moretab",function () {
    var _moretab_pop = $(".topbox").find(".moretab-pop");//更多栏目弹窗
    var _moretab_pop_close = $(".topbox").find(".moretab-pop-close");//更多栏目弹窗关闭按钮
    _moretab_pop.fadeIn(100);
    _moretab_pop_close.on("click",function () {
        _moretab_pop.fadeOut(100);
    });
});

//点击快速输入历史记录
$(".topbox").on("click",".search-pop-history-list-word",function () {
    var _this = $(this);
    var this_val = _this.text();
    $(".topbox").find(".index-top-search-input").val(this_val);
    $(".topbox").find(".index-top-search-input").focus();
});

//表单输入显示清除按钮
$(".form-box-input").on("focusout input propertychange",function () {
    var _this = $(this);
    var thisclear = _this.parents(".form-box").find(".form-box-input-clear");
    var thisval = _this.val();
    if(thisval.length > 0){
        thisclear.show();
    }else{
        thisclear.hide();
    }
});
$(".form-box-input-clear").on("click",function () {
    var _this = $(this);
    var thisinput = _this.parents(".form-box").find(".form-box-input");
    thisinput.val("");
    _this.hide();
    thisinput.focus();
});

//表单密码显示隐藏按钮
$(".form-box-input-eye").on("click",function () {
    var _this = $(this);
    var thisinput = _this.parents(".form-box").find(".form-box-input");
    if(_this.is(".icon-unlook")){
        //隐藏变显示
        _this.removeClass("icon-unlook").addClass("icon-look");
        thisinput.attr({"type":"text"});
    }else if(_this.is(".icon-look")){
        //显示变隐藏
        _this.removeClass("icon-look").addClass("icon-unlook");
        thisinput.attr({"type":"password"});
    }
});

//pullrefresh内的a标签点击
$("#pullrefresh").on("tap","a",function () {
    var href = $(this).attr("href");
    window.location.href = href;
});

//写cookie
function setCookie(name,value)
{
    var Days = 30;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days*24*60*60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}

//读取cookie
function getCookie(name)
{
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}

//删除cookie
function delCookie(name)
{
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval=getCookie(name);
    if(cval!=null)
        document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}

//检测是否登录
function check_login() {
    var user_id = getCookie("chehu_id");
    if(user_id){
        //已登录
        var photo = getCookie("chehu_photo");//头像链接
        var mobile = getCookie("chehu_mobile");//用户电话
        var user_name = getCookie("chehu_username");//用户昵称
        $(".topbox").find(".my-top-headimg").attr({"style":"background: url(" + photo + ") no-repeat center; background-size: cover;"});//设置弹窗头像
        if(user_name){
            $(".topbox").find(".my-top-name").text(user_name);//设置弹窗昵称
        }else{
            $(".topbox").find(".my-top-name").text(mobile);//设置弹窗电话
        }
    }
}

//注销登录
$(".topbox").on("click","#member_quit_btn",function () {

    delCookie("chehu_mobile");
    delCookie("chehu_password");
    delCookie("chehu_id");
    delCookie("chehu_username");
    delCookie("chehu_photo");
    alert("退出成功");
    window.location.href = "index.html";

});

//获取手机型号
function get_system() {
    //Android、iOS
    var system = "";
    var device_type = navigator.userAgent;//获取userAgent信息
    if(device_type.indexOf("iPhone") >= 0){
        system = "iOS";
    }else if(device_type.indexOf("iPad") >= 0){
        system = "iOS";
    }else if(device_type.indexOf("Android") >= 0){
        system = "Android";
    }
    return system;
}

//插入浏览记录
function set_browser_record(content_id,isbanner,isad,fromtype) {
    if(!fromtype){
        return false;
    }
    //是否来自banner
    if(isbanner == 1){
        isbanner = 1;
    }else{
        isbanner = 0;
    }
    //是否来自广告
    if(isad == 1){
        isad = 1;
    }else{
        isad = 0;
    }
    var browse_data = {
        user_id:getCookie("chehu_id"),
        platform:3,//默认公众号3
        // knowledge_id:content_id,
        is_banner:isbanner,
        is_ad:isad,
        mobile_system:get_system()
    };
    //浏览来源
    //资讯：knowledge_id
    //测评：evaluation_id
    //快讯：news_flash_id
    //美女图片：girl_img_id
    //音频视频：forum_id
    //快讯：news_flash_id
    if(fromtype == "knowledge_id"){
        browse_data.knowledge_id = content_id;
    }else if(fromtype == "evaluation_id"){
        browse_data.evaluation_id = content_id;
    }else if(fromtype == "news_flash_id"){
        browse_data.news_flash_id = content_id;
    }else if(fromtype == "girl_img_id"){
        browse_data.girl_img_id = content_id;
    }else if(fromtype == "forum_id"){
        browse_data.forum_id = content_id;
    }else if(fromtype == "news_flash_id"){
        browse_data.news_flash_id = content_id;
    }else{
        browse_data.knowledge_id = "-1";
    }
    //浏览记录
    $.ajax({
        url:SERVERURL + '/v2/api/carapi/getBrowseRecord',
        dataType:'JSON',
        type:'POST',
        data:browse_data,
        success:function(res){
            if(typeof res == "string"){
                res = JSON.parse(res)
            }
            console.log(res);
            // return;
        },
        error:function(XMLHttpRequest, textStatus, errorThrown) {
            //console.log(XMLHttpRequest.status);
            //console.log(XMLHttpRequest.readyState);
            //console.log(textStatus);
        }
    });
}

//插入分享记录
function set_share_record(content_id,fromtype) {
    if(!fromtype){
        return false;
    }
    var share_data = {
        user_id:getCookie("chehu_id"),
        platform:3,//默认公众号3
        // knowledge_id:content_id,
        // is_banner:isbanner,
        // is_ad:isad,
        mobile_system:get_system()
    };
    //浏览来源
    //资讯：knowledge_id
    //测评：evaluation_id
    //快讯：news_flash_id
    //美女图片：girl_img_id
    //音频视频：forum_id
    //快讯：news_flash_id
    if(fromtype == "knowledge_id"){
        share_data.knowledge_id = content_id;
    }else if(fromtype == "evaluation_id"){
        share_data.evaluation_id = content_id;
    }else if(fromtype == "news_flash_id"){
        share_data.news_flash_id = content_id;
    }else if(fromtype == "girl_img_id"){
        share_data.girl_img_id = content_id;
    }else if(fromtype == "forum_id"){
        share_data.forum_id = content_id;
    }else if(fromtype == "news_flash_id"){
        share_data.news_flash_id = content_id;
    }else{
        share_data.knowledge_id = "-1";
    }
    //分享记录
    $.ajax({
        url:SERVERURL + '/v2/api/carapi/countShareRecord',
        dataType:'JSON',
        type:'POST',
        data:share_data,
        success:function(res){
            if(typeof res == "string"){
                res = JSON.parse(res)
            }
            console.log(res);
            // return;
        },
        error:function(XMLHttpRequest, textStatus, errorThrown) {
            //console.log(XMLHttpRequest.status);
            //console.log(XMLHttpRequest.readyState);
            //console.log(textStatus);
        }
    });
}

//微信分享初始标题
var wxshare = {
    title:"【爱车乎】新能源汽车第一资讯平台",
    desc:"车乎专注于为广大用户提供新能源汽车行业资讯和新能源汽车使用指南、导购的专业垂直平台！",
    link:"http://www.chehuvip.com/chehu_wx/index.html",
    imgurl:"http://www.chehuvip.com/chehu_wx/Assets/Images/chehu_logo.png"
};